import React, { useState, useEffect } from 'react';
import { Dormitory, dormitoryTypeOptions, dormitoryStatusOptions } from '../../shared/models';

interface AddEditDormitoryModalProps {
  isOpen: boolean;
  isEditing: boolean;
  dormitory: Dormitory | null;
  buildings: string[];
  onClose: () => void;
  onSave: (dormitoryData: any) => void;
}

const AddEditDormitoryModal: React.FC<AddEditDormitoryModalProps> = ({
  isOpen,
  isEditing,
  dormitory,
  buildings,
  onClose,
  onSave
}) => {
  // 表单数据状态
  const [formData, setFormData] = useState({
    building: '',
    roomNumber: '',
    type: 'male' as const,
    capacity: 4,
    floor: 1,
    supervisor: '',
    phoneNumber: '',
    status: 'active' as const,
    notes: ''
  });

  // 表单验证错误状态
  const [errors, setErrors] = useState<Record<string, string>>({});

  // 当编辑的宿舍变化时，更新表单数据
  useEffect(() => {
    if (isEditing && dormitory) {
      setFormData({
        building: dormitory.building || '',
        roomNumber: dormitory.roomNumber || '',
        type: dormitory.type || 'male',
        capacity: dormitory.capacity || 4,
        floor: dormitory.floor || 1,
        supervisor: dormitory.supervisor || '',
        phoneNumber: dormitory.phoneNumber || '',
        status: dormitory.status || 'active',
        notes: dormitory.notes || ''
      });
    } else {
      // 添加模式时重置表单
      setFormData({
        building: buildings.length > 0 ? buildings[0] : '',
        roomNumber: '',
        type: 'male',
        capacity: 4,
        floor: 1,
        supervisor: '',
        phoneNumber: '',
        status: 'active',
        notes: ''
      });
    }
    // 重置错误信息
    setErrors({});
  }, [isEditing, dormitory, buildings]);

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: name === 'capacity' || name === 'floor' ? parseInt(value) || 1 : value
    }));
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[name];
        return newErrors;
      });
    }
  };

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {};

    if (!formData.building.trim()) {
      newErrors.building = '楼栋名称不能为空';
    }

    if (!formData.roomNumber.trim()) {
      newErrors.roomNumber = '房间号不能为空';
    }

    if (!formData.type) {
      newErrors.type = '请选择宿舍类型';
    }

    if (formData.capacity <= 0) {
      newErrors.capacity = '容量必须大于0';
    }

    if (formData.floor <= 0) {
      newErrors.floor = '楼层必须大于0';
    }

    if (!formData.status) {
      newErrors.status = '请选择宿舍状态';
    }

    // 验证手机号格式（如果填写）
    if (formData.phoneNumber && !/^1[3-9]\d{9}$/.test(formData.phoneNumber)) {
      newErrors.phoneNumber = '请输入有效的手机号';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理保存
  const handleSave = () => {
    if (validateForm()) {
      onSave(formData);
    }
  };

  // 处理模态框关闭
  const handleClose = () => {
    setErrors({});
    onClose();
  };

  // 阻止事件冒泡
  const handleModalClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  if (!isOpen) return null;

  return (
    <div className="modal-overlay" onClick={handleClose}>
      <div className="modal-content" onClick={handleModalClick}>
        <div className="modal-header">
          <h2 className="modal-title">
            {isEditing ? '编辑宿舍' : '添加宿舍'}
          </h2>
          <button className="modal-close" onClick={handleClose}>
            ×
          </button>
        </div>
        <div className="modal-body">
          <form onSubmit={(e) => { e.preventDefault(); handleSave(); }}>
            <div className="form-row">
              <div className="form-group">
                <label className="form-label" htmlFor="building">
                  楼栋 <span style={{ color: 'red' }}>*</span>
                </label>
                <select
                  id="building"
                  name="building"
                  className={`form-select ${errors.building ? 'error' : ''}`}
                  value={formData.building}
                  onChange={handleInputChange}
                >
                  {buildings.length > 0 ? (
                    buildings.map(building => (
                      <option key={building} value={building}>{building}</option>
                    ))
                  ) : (
                    <option value="">请选择楼栋</option>
                  )}
                </select>
                {errors.building && (
                  <div className="error-message">{errors.building}</div>
                )}
              </div>
              
              <div className="form-group">
                <label className="form-label" htmlFor="roomNumber">
                  房间号 <span style={{ color: 'red' }}>*</span>
                </label>
                <input
                  type="text"
                  id="roomNumber"
                  name="roomNumber"
                  className={`form-input ${errors.roomNumber ? 'error' : ''}`}
                  value={formData.roomNumber}
                  onChange={handleInputChange}
                  placeholder="请输入房间号"
                />
                {errors.roomNumber && (
                  <div className="error-message">{errors.roomNumber}</div>
                )}
              </div>
            </div>

            <div className="form-row">
              <div className="form-group">
                <label className="form-label" htmlFor="type">
                  宿舍类型 <span style={{ color: 'red' }}>*</span>
                </label>
                <select
                  id="type"
                  name="type"
                  className={`form-select ${errors.type ? 'error' : ''}`}
                  value={formData.type}
                  onChange={handleInputChange}
                >
                  {dormitoryTypeOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
                {errors.type && (
                  <div className="error-message">{errors.type}</div>
                )}
              </div>
              
              <div className="form-group">
                <label className="form-label" htmlFor="capacity">
                  容量 <span style={{ color: 'red' }}>*</span>
                </label>
                <input
                  type="number"
                  id="capacity"
                  name="capacity"
                  className={`form-input ${errors.capacity ? 'error' : ''}`}
                  value={formData.capacity}
                  onChange={handleInputChange}
                  min="1"
                  placeholder="请输入容量"
                />
                {errors.capacity && (
                  <div className="error-message">{errors.capacity}</div>
                )}
              </div>
            </div>

            <div className="form-row">
              <div className="form-group">
                <label className="form-label" htmlFor="floor">
                  楼层 <span style={{ color: 'red' }}>*</span>
                </label>
                <input
                  type="number"
                  id="floor"
                  name="floor"
                  className={`form-input ${errors.floor ? 'error' : ''}`}
                  value={formData.floor}
                  onChange={handleInputChange}
                  min="1"
                  placeholder="请输入楼层"
                />
                {errors.floor && (
                  <div className="error-message">{errors.floor}</div>
                )}
              </div>
              
              <div className="form-group">
                <label className="form-label" htmlFor="status">
                  状态 <span style={{ color: 'red' }}>*</span>
                </label>
                <select
                  id="status"
                  name="status"
                  className={`form-select ${errors.status ? 'error' : ''}`}
                  value={formData.status}
                  onChange={handleInputChange}
                >
                  {dormitoryStatusOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
                {errors.status && (
                  <div className="error-message">{errors.status}</div>
                )}
              </div>
            </div>

            <div className="form-row">
              <div className="form-group">
                <label className="form-label" htmlFor="supervisor">
                  管理员
                </label>
                <input
                  type="text"
                  id="supervisor"
                  name="supervisor"
                  className="form-input"
                  value={formData.supervisor}
                  onChange={handleInputChange}
                  placeholder="请输入管理员姓名"
                />
              </div>
              
              <div className="form-group">
                <label className="form-label" htmlFor="phoneNumber">
                  联系电话
                </label>
                <input
                  type="tel"
                  id="phoneNumber"
                  name="phoneNumber"
                  className={`form-input ${errors.phoneNumber ? 'error' : ''}`}
                  value={formData.phoneNumber}
                  onChange={handleInputChange}
                  placeholder="请输入联系电话"
                />
                {errors.phoneNumber && (
                  <div className="error-message">{errors.phoneNumber}</div>
                )}
              </div>
            </div>

            <div className="form-group">
              <label className="form-label" htmlFor="notes">
                备注
              </label>
              <textarea
                id="notes"
                name="notes"
                className="form-textarea"
                value={formData.notes}
                onChange={handleInputChange}
                placeholder="请输入备注信息（可选）"
                rows={4}
              />
            </div>
          </form>
        </div>
        <div className="modal-footer">
          <button className="btn-secondary" onClick={handleClose}>
            取消
          </button>
          <button className="btn-primary" onClick={handleSave}>
            {isEditing ? '更新' : '保存'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default AddEditDormitoryModal;